package ruralmanagementsystem.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import ruralmanagementsystem.result.Result;
import ruralmanagementsystem.utils.AliOssUtil;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/common")
@CrossOrigin
@Slf4j
public class CommonController {

    @Autowired
    private AliOssUtil aliOssUtil;

    //文件上传通用接口
    @PostMapping("/upload")
    public Result<String> uploadFile(MultipartFile file){
        log.info("文件上传：{}", file);
        try {
            //获取原始文件名
            String originalFilename = file.getOriginalFilename();
            //获取扩展名
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String objectName = UUID.randomUUID().toString() + extension;
            String fileURL = aliOssUtil.upload(file.getBytes(), objectName);
            return Result.success(fileURL);
        } catch (IOException e) {
            log.error("文件上传失败{}", e);
        }
        return Result.error("文件上传失败");
    }
}
